package io.netty.test.main.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author LuoYu
 * @date 2018/10/27 19:30
 * <p>
 * Description:
 */
public class NIOServer {

    private ServerSocketChannel server;

    private Selector selector;

    private ChannelHandler handler;


    public NIOServer(int port, ChannelHandler handler) {
        ServerSocketChannel acceptorServer;
        try {
            acceptorServer = ServerSocketChannel.open();
            acceptorServer.socket().bind(new InetSocketAddress(port));
            acceptorServer.configureBlocking(false);
            this.server = acceptorServer;
            this.selector = Selector.open();
            this.handler = handler;
            server.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 轮询注册到select上的注册事件 selectionKey
     *
     */
    public void listen() throws IOException {
        for (; ; ) {
            // select is a blocking method , get the number of registered channels
            // until there is an event ready for one of the registered channels
            int wait = selector.select();
            if (wait > 0) {
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    try {
                        if (key.isAcceptable()) {
                            handler.onAccept(key);
                        } else if (key.isWritable()) {
                            handler.onWrite(key);
                        } else if (key.isReadable()) {
                            handler.onRead(key);
                        } else if (key.isConnectable()) {
                            handler.onConnect(key);
                        }
                    } catch (IOException e) {
                        key.cancel();
                    }

                }
            }
        }
    }

    public interface ChannelHandler {
        void onAccept(SelectionKey event) throws IOException;

        void onRead(SelectionKey event) throws IOException;

        void onConnect(SelectionKey event) throws IOException;

        void onWrite(SelectionKey event) throws IOException;
    }

    public static void main(String[] args) throws IOException {
        NIOServer server = new NIOServer(8080, new ChannelHandler() {
            @Override
            public void onAccept(SelectionKey event) throws IOException {
                ServerSocketChannel acceptorServerRef = (ServerSocketChannel) event.channel();
                SocketChannel client = acceptorServerRef.accept();
                client.configureBlocking(false);
                client.register(event.selector(), SelectionKey.OP_READ);
            }

            @Override
            public void onRead(SelectionKey event) throws IOException {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                SocketChannel client = (SocketChannel) event.channel();
                int len = client.read(buffer);
                if (len > 0) {
                    buffer.flip();
                    String content = new String(buffer.array(), 0, len);
                    System.out.println(content);
                    client.register(event.selector(), SelectionKey.OP_WRITE);
                }
                buffer.clear();
            }

            @Override
            public void onConnect(SelectionKey event) throws IOException {

            }

            @Override
            public void onWrite(SelectionKey event) throws IOException {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                SocketChannel client = (SocketChannel) event.channel();
                client.write((ByteBuffer) buffer.put("fuck u".getBytes()).flip());
                client.register(event.selector(), SelectionKey.OP_READ);
                buffer.clear();
            }
        });
        server.listen();


    }
}
